package com.hutou.chuangke.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.adapter.GridImageAdapter;
import com.hutou.chuangke.androidbug.AndroidBug5497Workaround;
import com.hutou.chuangke.dialog.NetDailog;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.RequestThreadPool;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.uitl.CommonUtils;
import com.hutou.chuangke.uitl.FullyGridLayoutManager;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
//import com.luck.picture.lib.model.FunctionConfig;
//import com.luck.picture.lib.model.LocalMediaLoader;
//import com.luck.picture.lib.model.PictureConfig;
//import com.yalantis.ucrop.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/24.
 */

public class FeedbackActivity extends BaseActivity implements View.OnClickListener{
    Context mContext;
    Toolbar toolbar;
    RecyclerView recycler;
    RequestFeedback requestFeedback;

    EditText feedback_et,phonenumber;
    TextView feedback_size_tv;
    TextView commit_tv;
    boolean noteIsempty=true;
    boolean phonenumIsempty=true;
    String strphone,strnote;
    private GridImageAdapter adapter;
    private ArrayList<String> imageurls = new ArrayList<>();
    private static final int REQUEST_CODE = 0;
    private NetDailog netDilaog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mContext = FeedbackActivity.this;
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        AndroidBug5497Workaround.assistActivity(this);
    }

    private void initView() {
        netDilaog = new NetDailog(mContext);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setPadding(0, CommonUtils.getStatusHeight(FeedbackActivity.this), 0, 0);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.actionbar_back);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        showQuickControl(false);

        recycler = (RecyclerView) findViewById(R.id.recycler);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext,3, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(mContext , onAddPicClickListener);
        adapter.setSelectMax(9);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext,4,GridLayoutManager.VERTICAL,false);
//        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(gridLayoutManager);
        recycler.setAdapter(adapter);

        feedback_et = (EditText) findViewById(R.id.feedback_et);
        phonenumber = (EditText) findViewById(R.id.phonenumber);
        feedback_size_tv = (TextView) findViewById(R.id.feedback_size_tv);
        commit_tv = (TextView) findViewById(R.id.commit_tv);
        commit_tv.setOnClickListener(this);
        feedback_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                feedback_size_tv.setText(charSequence.length()+"/400");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.length()>0){
                    noteIsempty = false;
                }else{
                    noteIsempty = true;
                }
            }
        });
        phonenumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.length()>0){
                    phonenumIsempty = false;
                }else{
                    phonenumIsempty = true;
                }
            }
        });
    }

    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    public void Multiselect() {
        ImgSelConfig config = new ImgSelConfig.Builder(this, loader)
                // 是否多选
                .multiSelect(true)
                .btnText("Confirm")
                // 确定按钮背景色
                //.btnBgColor(Color.parseColor(""))
                // 确定按钮文字颜色
                .btnTextColor(Color.WHITE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#C62828"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("Images")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#C62828"))
                .allImagesText("All Images")
                .needCrop(true)
                .cropSize(1, 1, 200, 200)
                // 第一个是否显示相机
                .needCamera(true)
                // 最大选择图片数量
                .maxNum(5)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

            // 测试Fresco。可不理会
//            draweeView.setImageURI(Uri.parse("file://"+pathList.get(0)));
            imageurls.clear();
            for (String path : pathList) {
                imageurls.add(path);
            }
            adapter.setList(imageurls);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new
            GridImageAdapter.onAddPicClickListener() {
                @Override
                public void onAddPicClick(int type, int position) {
                    switch (type){
                        case 0:
                            Multiselect();
                            break;
                        case 1:
                            imageurls.remove(position);
                            adapter.notifyItemRemoved(position);
                            break;
                    }
                }
            };

    @Override
    public void onClick(View view) {
        if(view == commit_tv){
            String note = feedback_et.getText().toString();
            String phone = phonenumber.getText().toString();
            if(note.isEmpty()){
                Toast.makeText(mContext,"请填写内容",Toast.LENGTH_SHORT).show();
                return;
            }else if(phone.isEmpty()){
                Toast.makeText(mContext,"请填写联系方式",Toast.LENGTH_SHORT).show();
                return;
            }
            strnote = note;
            strphone = phone;
            netDilaog.show();
            requestFeedback = new RequestFeedback();
            requestFeedback.execute();
        }
    }



    class RequestFeedback extends AsyncTask<Void , Void ,Boolean>{

        @Override
        protected Boolean doInBackground(Void... voids) {
            try{
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.
                        feedback(MainApplication.id,MainApplication.sid,strphone,strphone),imageurls,"photos");
                String flag = jsonObject.get("flag").getAsString();
                if(flag.endsWith("1")){
                    return true;
                }else{
                    return  false;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            netDilaog.dismiss();
            if(aBoolean){
                Toast.makeText(mContext,"提交成功",Toast.LENGTH_SHORT).show();
                FeedbackActivity.this.finish();
            }else{
                Toast.makeText(mContext,"提交失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(requestFeedback != null){
            requestFeedback.cancleTask();
        }
    }
}
